package com.r2coding.web.validator;

import com.r2coding.core.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 统一的参数校验器
 * @Create on : 2023/9/17 10:16
 **/
@SpringBootConfiguration
@Slf4j
public class WebValidatorConfig {
    private static final String FAIL_FAST_KEY = "hibernate.validator.fail_fast";

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
        postProcessor.setValidator(pan4jValidator());
        log.info("The hibernate validator is loaded successfully!");
        return postProcessor;
    }

    private Validator pan4jValidator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .addProperty(FAIL_FAST_KEY, Constants.TRUE_STR)
                .buildValidatorFactory();
        return validatorFactory.getValidator();
    }
}
